// Reduce multiple spaces to one space.
// Date 09/10/2018
// By Ben

#include <iostream>

using namespace std;
using std::cout;
using std::endl;
using std::cin;

void ReduceSpaces(string &source){
	string sLine = "";
	string s0 = "";
	string buffer = "";
	int i = 0;
	int j = 0;

	//Append a last space if none is found.
	if (source[source.length() - 1] != ' '){
		source.append(" ");
	}

	for (i = 0; i < source.length(); i++){
		if (isspace(source[i])){

			//Reset variables
			j = 0;
			s0.clear();

			//Build a string ignoring spaces.
			while (j < buffer.length()){
				//Check we do not have a space in the string
				if (!isspace(buffer[j])){
					//Build string.
					s0 += buffer[j];
				}
				j++;
			}
			//Check for valid length
			if (s0.length() != 0){
				//Append one space after each string.
				sLine += s0 + " ";
			}
			//Clear buffer.
			buffer.clear();
		}
		else{
			//Build string buffer.
			buffer += source[i];
		}
	}
	s0.clear();
	source = sLine;
}

int main(int argc, char *argv[]){
	string s0 = " The quick   brown fox jumps,  Over the     lazy    dog.";
	std::cout << "Original string : " << endl << s0.c_str() << endl;
	//Reduce the whitespace in the string above.
	ReduceSpaces(s0);
	std::cout << endl;
	//Show output result.
	std::cout << "Fixed string: " << endl << s0.c_str() << endl;

	system("pause");
	return 0;
}